import { Color3, Engine, Animation, Vector3, Mesh, Scene, ArcRotateCamera, PointLight, StandardMaterial, Texture, ShaderMaterial, IAnimationKey } from 'babylonjs'

// 动画
export class Demo4 {
  private dom: HTMLCanvasElement
  private engine: Engine
  private scene: Scene
  private camera: ArcRotateCamera

  constructor(dom: HTMLCanvasElement) {
    this.dom = dom
    this.engine = new Engine(this.dom, true)  // 设置引擎
    this.scene = new Scene(this.engine)   // 创建场景
    this.camera = new ArcRotateCamera("Camera", 0, 0, 100, Vector3.Zero(), this.scene); // 创建相机
    this.camera.attachControl(this.dom, false)  // 把相机放到画布

    const light = new PointLight("Omni", new Vector3(0, 100, 100), this.scene);

    const box1 = Mesh.CreateBox("Box1", 10.0, this.scene);
    box1.position.x = -20;
    const box2 = Mesh.CreateBox("Box2", 10.0, this.scene);
    box2.position.x = 20;

    var materialBox = new StandardMaterial("texture1", this.scene);
    materialBox.diffuseColor = new Color3(0, 1, 0);//Green
    var materialBox2 = new StandardMaterial("texture2", this.scene);

    box1.material = materialBox;
    box2.material = materialBox2;

    // 以30 FPS的速度创建缩放动画  （名称，变化的值，频率，【不确定的数值】，结束后的处理类型）
    // Animation.ANIMATIONLOOPMODE_CYCLE  表示周期，往复
    //Animation.ANIMATIONLOOPMODE_CONSTANT  表示只执行一次
    const animationBox = new Animation("tutoAnimation", "scaling.x", 60, Animation.ANIMATIONTYPE_FLOAT,
      Animation.ANIMATIONLOOPMODE_RELATIVE);

    // 记录动画的数组
    const keys: IAnimationKey[] = []

    keys.push({
      frame: 0,  // 关键帧
      value: 1   // 值
    })

    keys.push({
      frame: 20,  // 关键帧
      value: 0.2   // 值
    })

    keys.push({
      frame: 100,
      value: 1
    });

    // 添加动画
    animationBox.setKeys(keys)
    box1.animations.push(animationBox)

    this.scene.beginAnimation(box1, 0, 100, true)

    this.scene.registerBeforeRender(function () {

      // 随机颜色动画
      materialBox2.diffuseColor = new Color3(Math.random(), Math.random(), Math.random());

    });

    window.addEventListener('resize', () => {
      this.engine.resize();
    })
  }

  render() {
    // 引擎渲染场景
    this.engine.runRenderLoop(() => {
      this.scene.render()
    })

  }




}


